//
//  PPAddPetTableViewController.m
//  pet
//
//  Created by 陈无忌 on 10/10/14.
//  Copyright (c) 2014 whalefin. All rights reserved.
//

#import "PPAddPetTableViewController.h"
#import "supportingHeadFiles.h"
#import "PPCameraAuthorization.h"
#import "QRCodeGenerator.h"
#import "PPZBarViewController.h"

@interface PPAddPetTableViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,UIPickerViewDataSource,UIPickerViewDelegate,UITextFieldDelegate,UITextViewDelegate,UIGestureRecognizerDelegate,UIActionSheetDelegate,ScanQRCodeDelegate>
//static view
@property (weak, nonatomic) IBOutlet UIImageView *petAvatarImageView;
@property (weak, nonatomic) IBOutlet UITextField *petNameTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *petAgeTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *petBreedTextFiled;
@property (nonatomic) int gender;
@property (weak, nonatomic) IBOutlet UIButton *choseMaleButton;
@property (weak, nonatomic) IBOutlet UIButton *choseFemaleButton;
@property (weak, nonatomic) IBOutlet UITextView *introductionTextView;
@property (weak, nonatomic) IBOutlet UILabel *hintLabel;
@property (weak, nonatomic) IBOutlet UITextField *petLengthTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *petWeightTextFiled;
@property (weak, nonatomic) IBOutlet UITextField *petColorTextFiled;

@property (strong, nonatomic) NSString *petCode;
//
@property (weak, nonatomic) PPSystemConfiguraton *config;
@property (strong, nonatomic) UIImagePickerController *imagePicker;
@property (strong, nonatomic) NSString *imgPath;

//breed
@property (nonatomic, strong) NSString *petBreed;
@property (nonatomic, strong) NSString *petType;
@property (nonatomic, strong) NSArray *petBreedArray;
@property (nonatomic, strong) NSArray *petTypeArray;
//UIPicker
@property (nonatomic, strong) UIPickerView *petPickerView;
@property (strong, nonatomic) UIToolbar *toolBar;
@property (strong, nonatomic) UIBarButtonItem *cancelButton;
@property (strong, nonatomic) UIBarButtonItem *doneButton;
//number pad
@property (strong, nonatomic) UIToolbar *numPadToolBar;

@property (strong, nonatomic) UIDatePicker *datePicker;
@property (nonatomic, strong) UIToolbar *dateToolBar;
@property (nonatomic, strong) UIBarButtonItem *dateDoneButton;
@property (nonatomic, strong) UIBarButtonItem *dateCancelButton;
@property (nonatomic, strong) NSDateFormatter *formatter;
@end

@implementation PPAddPetTableViewController

//date picker view
- (NSDateFormatter *)formatter
{
    if (!_formatter) {
        _formatter = [[NSDateFormatter alloc] init];
        NSTimeZone *timeZone = [NSTimeZone localTimeZone];
        [_formatter setTimeZone:timeZone];
        [_formatter setDateFormat:@"yyyy/MM/dd"];
    }
    return _formatter;
}
//UIDatePicker
- (UIDatePicker *)datePicker
{
    if (!_datePicker) {
        _datePicker = [[UIDatePicker alloc] initWithFrame:CGRectMake(0, 0, 320, 260)];
    }
    return _datePicker;
}
- (UIToolbar *)dateToolBar
{
    if (!_dateToolBar) {
        _dateToolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        NSArray *toolBarItems = [[NSArray alloc] initWithObjects:self.dateCancelButton, space, self.dateDoneButton, nil];
        [_dateToolBar setItems:toolBarItems];
    }
    return _dateToolBar;
}
- (UIBarButtonItem *)dateCancelButton
{
    if (!_dateCancelButton) {
        _dateCancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelDateButtonPressed:)];
    }
    return _dateCancelButton;
}
- (UIBarButtonItem *)dateDoneButton
{
    if (!_dateDoneButton) {
        _dateDoneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneDateButtonPressed:)];
    }
    return _dateDoneButton;
}

- (void)cancelDateButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.petAgeTextFiled isFirstResponder]) {
        [self.petAgeTextFiled resignFirstResponder];
    }
}
- (void)doneDateButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.petAgeTextFiled isFirstResponder]) {
        [self.petAgeTextFiled resignFirstResponder];
        self.petAgeTextFiled.text = [self.formatter stringFromDate:self.datePicker.date];
        //        self.my.Userbirthday=self.userBirthTextField.text;
        //        NSLog(@"___%@",self.my.Userbirthday);
    }
}

-(UIPickerView *)petPickerView
{
    if (!_petPickerView) {
        _petPickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, 0, 320, 260)];
        _petPickerView.delegate = self;
        _petPickerView.dataSource = self;
    }
    return _petPickerView;
}
-(UIToolbar *)toolBar
{
    if (!_toolBar) {
        _toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        NSArray *toolBarItems = [[NSArray alloc] initWithObjects:self.cancelButton, space, self.doneButton, nil];
        [_toolBar setItems:toolBarItems];
    }
    return _toolBar;
}
- (UIBarButtonItem *)cancelButton
{
    if (!_cancelButton) {
        _cancelButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCancel target:self action:@selector(cancelButtonPressed:)];
    }
    return _cancelButton;
}
- (UIBarButtonItem *)doneButton
{
    if (!_doneButton) {
        _doneButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(doneButtonPressed:)];
    }
    return _doneButton;
}

- (void)cancelButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.petBreedTextFiled isFirstResponder]) {
        [self.petBreedTextFiled resignFirstResponder];
    }
    
}
- (void)doneButtonPressed:(UIBarButtonItem *)sender
{
    if ([self.petBreedTextFiled isFirstResponder]) {
        [self.petBreedTextFiled resignFirstResponder];
        
        self.petType = [self.petTypeArray objectAtIndex:[self.petPickerView selectedRowInComponent:0]];
        self.petBreed = [self.petBreedArray objectAtIndex:[self.petPickerView selectedRowInComponent:1]];
        self.petBreedTextFiled.text = [NSString stringWithFormat:@"%@ %@",self.petType,self.petBreed];
    }
}

-(UIToolbar *)numPadToolBar
{
    if (!_numPadToolBar) {
        _toolBar = [[UIToolbar alloc] initWithFrame:CGRectMake(0, 0, 320, 40)];
        UIBarButtonItem *space = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil];
        UIBarButtonItem *returnButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone target:self action:@selector(returnPadNum)];
        NSArray *toolBarItems = [[NSArray alloc] initWithObjects:space, space, returnButton, nil];
        [_toolBar setItems:toolBarItems];
    }
    return _toolBar;
}

-(void)returnPadNum
{
    [self.petLengthTextFiled resignFirstResponder];
    [self.petWeightTextFiled resignFirstResponder];
    [self.petAgeTextFiled resignFirstResponder];
}

- (UIImagePickerController *)imagePicker
{
    if (!_imagePicker) {
        _imagePicker = [[UIImagePickerController alloc] init];
        
        _imagePicker.allowsEditing = YES;
        _imagePicker.delegate = self;
    }
    return _imagePicker;
}

-(PPSystemConfiguraton *)config
{
    if (!_config) {
        _config = [PPSystemConfiguraton sharedSystemConfiguration];
    }
    return _config;
}

-(void)viewDidLayoutSubviews
{
    [super viewDidLayoutSubviews];
    
    if ([self.tableView respondsToSelector:@selector(setSeparatorInset:)]) {
        [self.tableView setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([self.tableView respondsToSelector:@selector(setLayoutMargins:)]) {
        [self.tableView setLayoutMargins:UIEdgeInsetsZero];
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.choseMaleButton addTarget:self action:@selector(choseMale:) forControlEvents:UIControlEventTouchUpInside];
    [self.choseFemaleButton addTarget:self action:@selector(choseFemale:) forControlEvents:UIControlEventTouchUpInside];
    self.choseMaleButton.tag = 0;
    self.choseFemaleButton.tag = 1;
    self.gender = 0;
    [self.choseMaleButton setImage:[UIImage imageNamed:@"maleBig"] forState:UIControlStateNormal];
    [self.choseFemaleButton setImage:[UIImage imageNamed:@"female"] forState:UIControlStateNormal];
    
    [self textFiledDelegate];
    [self staticViewSet];
    
    self.petTypeArray = [PPPetTypeArrayList getType];
    self.petBreedArray = [PPPetTypeArrayList getBreedWithType:[NSString stringWithFormat:@"%@",self.petTypeArray.firstObject]];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

-(void)staticViewSet
{
    UITapGestureRecognizer *recognizer = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(imageSet)];
    self.petAvatarImageView.userInteractionEnabled = YES;
    recognizer.numberOfTouchesRequired = 1;
    recognizer.numberOfTapsRequired = 1;
    [self.petAvatarImageView addGestureRecognizer:recognizer];
    
    self.petBreedTextFiled.inputView = self.petPickerView;
    self.petBreedTextFiled.inputAccessoryView = self.toolBar;
    
    [self.petAvatarImageView setImage:[UIImage imageNamed:@"defaultAvatar"]];
    
    self.petLengthTextFiled.inputAccessoryView = self.numPadToolBar;
    self.petWeightTextFiled.inputAccessoryView = self.numPadToolBar;
    self.petAgeTextFiled.inputAccessoryView = self.numPadToolBar;
    
    self.petAgeTextFiled.inputView = self.datePicker;
    self.petAgeTextFiled.inputAccessoryView = self.dateToolBar;
    
}

-(void)textFiledDelegate
{
    self.petNameTextFiled.delegate = self;
    self.petAgeTextFiled.delegate = self;
    self.petBreedTextFiled.delegate = self;
    self.petLengthTextFiled.delegate = self;
    self.petWeightTextFiled.delegate = self;
    self.petColorTextFiled.delegate = self;

    self.introductionTextView.delegate = self;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)imageSet
{
    UIActionSheet *choiceSheet = [[UIActionSheet alloc] initWithTitle:nil
                                                             delegate:self
                                                    cancelButtonTitle:@"取消"
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:@"拍照", @"从相册中选取", nil];
    [choiceSheet showInView:self.tableView];
}

#pragma mark - Table view delegate
-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 14)];
    view.backgroundColor = [UIColor whiteColor];
    return view;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 14.0;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 3 && indexPath.section == 2) {
        PPZBarViewController *targetVC = [self.storyboard instantiateViewControllerWithIdentifier:@"zbarVC"];
        targetVC.delegate = self;
        [self.navigationController pushViewController:targetVC animated:YES];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}

#pragma mark - Pick view data soure
-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView//返回选择器组件数
{
    //    if ([pickerView isEqual:self.petPickerView])
    return 2;
    
}
-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component//选择器的选项个数
{
    //    if ([pickerView isEqual:self.petPickerView])
    if (component == 0) {
        return self.petTypeArray.count;
    }else{
        return self.petBreedArray.count;
    }
}



-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
    if (component == 0) {
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
        UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
        [myLabel setText:[self.petTypeArray objectAtIndex:row]];
        myLabel.textAlignment = NSTextAlignmentCenter;
        myLabel.Font = [UIFont fontWithName:@"Arial" size:14];
        [myView addSubview:myLabel];
        return myView;
    }else{
        UIView *myView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 160, 44)];
        UILabel *myLabel = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 160, 44)];
        [myLabel setText:[self.petBreedArray objectAtIndex:row]];
        myLabel.textAlignment = NSTextAlignmentCenter;
        myLabel.Font = [UIFont fontWithName:@"Arial" size:14];
        [myView addSubview:myLabel];
        return myView;
    }
}

- (void)pickerView:(UIPickerView *)pickerView
      didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    //    if ([pickerView isEqual:self.petPickerView])
    if (component == 0) {
        self.petBreedArray = [PPPetTypeArrayList getBreedWithType:[NSString stringWithFormat:@"%@",[self.petTypeArray objectAtIndex:row]]];
        [self.petPickerView reloadComponent:1];
    }
}


#pragma mark - ActionSheet
-(void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 2) {
        return;
    }
    if (buttonIndex == 1) {
        self.imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    }else if (buttonIndex == 0){
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            if (IS_OS_7_OR_LATER) {
                [PPCameraAuthorization getCameraAuthorization];
                if (!self.config.isCameraValid) {
                    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"请在iPhone的“设置-隐私-相机”选项中，允许程序访问你的相机" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
                    [alert show];
                    return;
                }else{
                    [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
                }
            }else{
                [self.imagePicker setSourceType:UIImagePickerControllerSourceTypeCamera];
            }

        }else{
            [self.imagePicker setSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            
        }
    }
    [self presentViewController:self.imagePicker animated:YES completion:nil];
}

#pragma mark - UIImagePickContrillerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerEditedImage];
    [self.petAvatarImageView setImage:image];
//    self.imgPath = [self uploadUserAvatar:self.petAvatarImageView.image];
    image = nil;
    [self.imagePicker dismissViewControllerAnimated:YES completion:nil];
}

//获得图片本地沙箱路径
- (NSString *)uploadUserAvatar:(UIImage *)image
{
    NSData *data;
    if (UIImagePNGRepresentation(image).length > 2100000) {
        data = UIImageJPEGRepresentation(image, 0.5);
    }else{
        data = UIImagePNGRepresentation(image);
    }
    //图片保存的路径
    //这里将图片放在沙盒的documents文件夹中
    NSString * DocumentsPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    //文件管理器
    NSFileManager *fileManager = [NSFileManager defaultManager];
    //把刚刚图片转换的data对象拷贝至沙盒中 并保存为image.png
    [fileManager createDirectoryAtPath:DocumentsPath withIntermediateDirectories:YES attributes:nil error:nil];
    [fileManager createFileAtPath:[DocumentsPath stringByAppendingString:@"/petAvatar.png"] contents:data attributes:nil];
    //得到选择后沙盒中图片的完整路径 并返回
    return [[NSString alloc]initWithFormat:@"%@%@",DocumentsPath,  @"/petAvatar.png"];
}

//
#pragma mark - Scan Delegate
- (void)scanFinishedWithResult:(NSString *)resultString
{
    NSString *prefix = @"http://sfz.fundoing.cn/pet/info?id=";
    NSString *petCode;
    if ([resultString hasPrefix:prefix]) {
        petCode = [resultString substringFromIndex:35];
    }
    if (petCode) {
        self.petCode = petCode;
        [self alertShow:@"成功识别到二维码为有效二维码"];
    } else {
        [self alertShow:@"请确保二维码为宠缘提供的有效二维码"];
    }
}


#pragma mark - Custom IBAction
- (void)choseMale:(UIButton *)sender {
    self.gender = sender.tag;
    [self.choseMaleButton setImage:[UIImage imageNamed:@"maleBig"] forState:UIControlStateNormal];
    [self.choseFemaleButton setImage:[UIImage imageNamed:@"female"] forState:UIControlStateNormal];
}

- (void)choseFemale:(UIButton *)sender {
    self.gender = sender.tag;
    [self.choseMaleButton setImage:[UIImage imageNamed:@"male"] forState:UIControlStateNormal];
    [self.choseFemaleButton setImage:[UIImage imageNamed:@"femaleBig"] forState:UIControlStateNormal];
}

- (IBAction)createButtonClick:(id)sender {
    //first step check
    if (!self.petNameTextFiled.text.length > 0) {
        [self alertShow:@"请输入宠物的名字！"];
        return;
    }
    if (!self.petAgeTextFiled.text.length > 0) {
        [self alertShow:@"请输入宠物的生日！"];
        return;
    }
    if (!self.petBreedTextFiled.text.length > 0) {
        [self alertShow:@"请设置宠物的品种！"];
        return;
    }
    
    [HUD showUIBlockingIndicatorWithText:@"正在创建"];
    NSString *breeding = @"no";
    self.imgPath = [self uploadUserAvatar:self.petAvatarImageView.image];
    NSString *url = [PPAPIList getAPIList].PPSaveOrUpdatePetMsg;
    NSMutableDictionary *params =[[NSMutableDictionary alloc] initWithDictionary:@{
                             @"userId":@(self.config.userInfo.id),
                             @"birth":self.petAgeTextFiled.text,
                             @"petName":self.petNameTextFiled.text,
                             @"petType":self.petType,
                             @"petBreed":self.petBreed,
                             @"introduction":self.introductionTextView.text,
                             @"petGender":@(self.gender),
                             @"breeding":breeding,
                             }];
    if (self.petLengthTextFiled.text.length > 0) {
        [params setObject:@(self.petLengthTextFiled.text.doubleValue) forKey:@"petLong"];
    }
    if (self.petWeightTextFiled.text.length > 0) {
        [params setObject:@(self.petWeightTextFiled.text.doubleValue) forKey:@"weight"];
    }
    if (self.petColorTextFiled.text.length > 0) {
        [params setObject:self.petColorTextFiled.text forKey:@"color"];
    }
    if (self.petCode.length > 0) {
        [params setObject:self.petCode forKey:@"code"];
    }
    [httpRequst POST:url parameters:params imagePath:self.imgPath imageName:@"petAvatar" keyWords:@"petAvatar" success:^(AFHTTPRequestOperation *operation, id responseObject){
        NSNumber *processResult = responseObject[@"processResult"];
        if (processResult.boolValue) {
            //创建成功
            [self.config getPetListwithComepletion:^{
                [HUD hideUIBlockingIndicator];
                [self.navigationController popViewControllerAnimated:YES];
            }];
        }else{
            [PPHUD hudShowWithString:@"创建失败请重试" andView:self.view];
        }
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"reload" object:nil];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error){
        [PPHUD hudShowWithString:@"网络不给力" andView:self.view];
    }];
    
}

#pragma mark - Text Filed delegate
- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField
{
    if ([textField isEqual:self.petAgeTextFiled]) {
        [self.datePicker setDatePickerMode:UIDatePickerModeDate];
        [self.datePicker setMaximumDate:[NSDate date]];
        [self.datePicker setMinimumDate:nil];
        [self.formatter setDateFormat:@"yyyy/MM/dd"];
        NSDate *currentDate;
        if (textField.text.length > 0) {
            currentDate = [self.formatter dateFromString:self.petAgeTextFiled.text];
        }else{
            currentDate = [NSDate date];
        }
        [self.datePicker setDate:currentDate];
        
    }
    return YES;
}



-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    return YES;
}

#pragma mark - Text View delegate
-(BOOL)textViewShouldBeginEditing:(UITextView *)textView
{
    self.hintLabel.hidden = YES;
    return YES;
}

-(BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

{
    if ([text isEqualToString:@"\n"]) {
        if (textView.text.length > 0) {
            self.hintLabel.hidden = YES;
        }else{
            self.hintLabel.hidden = NO;
        }
        [textView resignFirstResponder];
        return NO;
    }
    return YES;
    
    
}
#pragma mark - Custom Method
-(void)alertShow:(NSString *)msg
{
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
    [alert show];
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
